<template>
  <div class="finance_page">
    <!-- 顶部卡片 -->
    <div class="topCard">
      <el-card>
        <template #header>
          <div class="clearfix">
            <div class="leftBox">
              <span class="leftText">财务数据</span>
              <span class="leftTip">所有交易成功的金额，微信侧将收取6‰的交易手续费</span>
            </div>
            <el-button class="rightBtn" type="primary" @click="getMoney">提现</el-button>
          </div>
        </template>
        <div class="cardList">
          <div v-for="(item, index) in cardList" :key="index" class="cardItem">
            <div class="cardDetal">
              <div class="cardMoney">{{ item.money }}</div>
              <div
                class="cardText"
                :title="item.title"
              >
                <span>{{ item.name }}</span>
                <img src="@/assets/images/shuoming.png" />
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <!-- 选项卡 -->
    <div class="tabList">
      <div class="rightSearch">
        <el-date-picker
          v-model="searchForm.time"
          type="month"
          placeholder="选择日期"
          value-format="YYYY-MM"
          @change="changeDate"
        />
      </div>
      <el-tabs v-model="searchForm.condition" @tab-click="handleClick">
        <el-tab-pane label="日汇款" name="1" />
        <el-tab-pane label="月汇款" name="2" />
      </el-tabs>
      <!-- 表格 -->
      <div class="tableBox">
        <el-table
          v-loading="tableLoading"
          :data="tableData"
          border
          :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
          tooltip-effect="dark"
          style="width: 100%"
          class="dataTable"
        >
          <el-table-column label="日期" width="220">
            <template #default="scope">{{ scope.row.time }}</template>
          </el-table-column>
          <el-table-column prop="income" label="收入（元）" width="220" />
          <el-table-column
            prop="expenditure"
            label="支出（元）"
            show-overflow-tooltip
          />
          <el-table-column label="操作" show-overflow-tooltip>
            <template #default="scope">
              <div class="btnList">
                <el-button link type="primary" @click="seeMore(scope.row)">查看</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- *****************弹框开始***************** -->
    <el-dialog v-model="isVisible" title="提现" width="30%">
      <el-form
        v-if="show"
        ref="formRef"
        :model="form"
        label-width="120px"
        size="small"
        :rules="rules"
      >
        <p class="text_tip">
          <span>提现至:</span>
          <span v-if="Number(privacyTime) === 0">{{
            hidden(details.bankCard, 3, 4)
          }}</span>
          <span v-else>{{ details.bankCard }}</span>
          <span style="margin-left: 40px">{{ details.bankName }}</span>
        </p>
        <el-form-item label="提现金额" prop="amount">
          <el-col :span="16">
            <el-input
              v-model="form.amount"
              maxlength="9"
              :placeholder="'可提现金额:' + cardList[2].money"
            />
          </el-col>
          <el-col :span="6" style="text-align: center">
            <span class="sub_text" @click="getAllAmount">全部提现</span>
          </el-col>
        </el-form-item>
      </el-form>
      <p v-else class="tips">您的账户尚未绑定银行卡，无法提现</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="confirm()">确定</el-button>
          <el-button @click="isVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="moneydio" title="账单详情" width="80%">
      <div class="content">
        <!-- 顶部搜索 -->
        <div class="toolbar">
          <!-- 顶部搜索 -->
          <el-form ref="moneyFormRef" :inline="true" :model="moneyForm">
            <el-form-item label="汇总日期时间">
              <el-date-picker
                v-model="moneyForm.time"
                value-format="YYYY-MM-DD"
                type="date"
                placeholder="选择日期"
              />
            </el-form-item>
            <el-form-item label="收支类型">
              <el-select v-model="moneyForm.income" placeholder="请选择">
                <el-option label="全部" :value="null" />
                <el-option label="收入" value="1" />
                <el-option label="支出" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="流水类型">
              <el-select v-model="moneyForm.state" placeholder="请选择">
                <el-option label="全部" :value="null" />
                <el-option label="支付" value="支付" />
                <el-option label="退款" value="退款" />
                <el-option label="提现" value="提现" />
              </el-select>
            </el-form-item>
            <el-form-item label-width="0">
              <el-button type="primary" plain @click="search">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!--  表格 -->
        <div class="content_table">
          <div class="table">
            <el-table
              v-loading="detailTableLoading"
              :data="tableDatas"
              border
              :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
              style="width: 100%"
            >
              <el-table-column prop="waterType" label="流水类型" />
              <el-table-column prop="orderFormid" label="订单ID" />
              <el-table-column prop="incomeType" label="收支类型" />
              <el-table-column prop="money" label="金额(元)" />
              <el-table-column prop="balance" label="余额(元)" />
              <el-table-column prop="time" label="入账时间" />
            </el-table>
            <div class="fenye">
              <el-pagination
                v-model:current-page="moneyForm.page"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="moneyForm.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="moneydio = false">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue'
import { useRouter } from 'vue-router'
import { getFinanceCount, getBank, withdrawal, getDetails } from '@/api/finance'

const router = useRouter()
const formRef = ref(null)
const moneyFormRef = ref(null)
const tableLoading = ref(false)
const detailTableLoading = ref(false)
const moneydio = ref(false)
const cardList = ref([
  {
    name: '累计营业额（元）',
    money: '0.00',
    title: '所有订单状态为待发货、待收货、交易成功的订单金额之和'
  },
  {
    name: '冻结金额（元）',
    money: '0.00',
    title: '用户确认收货后，金额将会解冻',
  },
  {
    name: '可提现金额（元）',
    money: '0.00',
    title: ''
  },
  {
    name: '提现中（元）',
    money: '0.00',
    title: '',
  }
])
const form = ref({
  amount: ''
})
const moneyForm = ref({
  time: '',
  income: '',
  state: '',
  page: 1,
  pageSize: 10
})
const total = ref(1)
const rules = ref({
  amount: [
    { required: true, message: '请输入提现金额', trigger: 'blur' }
  ]
})
const searchForm = ref({
  condition: '1', // 时间条件 1-日汇总 2-月汇总
  time: '' // 时间值
})
const tableData = ref([])
const tableDatas = ref([])
const isVisible = ref(false)
const details = ref([{}])
const show = ref(false)
const privacyTime = ref(0)

onBeforeMount(() => {
  getAll()
  getBankType()
  privacyTime.value = localStorage.getItem('privacyTime')
})
const handleSizeChange = (val) => {
  moneyForm.value.pageSize = val
  getAlls()
}
const handleCurrentChange = (val) => {
  moneyForm.value.page = val
  getAlls()
}
const handleClick = (tab, event) => {
  searchForm.value.type = tab.name
  getAll()
}
const changeDate = () => {
  getAll()
}
const search = () => {
  total.value = 1
  searchForm.value.page = 1
  getAlls()
}
// 查看
const seeMore = (row) => {
  moneydio.value = true
  moneyForm.value.time = row.time
  moneyForm.value.page = 1
  tableDatas.value = []
  total.value = 1
  getAlls()
}
// 提现
const getMoney = async () => {
  isVisible.value = true
  form.value.amount = ''
  // const res = await getWithdrawalDetails(this.searchForm);
  const res = await getBank({})
  if (JSON.stringify(res.data) === '{}') {
    show.value = false
  } else {
    show.value = true
    details.value = res.data
  }
}
// 提现确定
const confirm = async () => {
  if (show.value) {
    if (form.value.amount <= 0) {
      ElMessage({
        message: '请输入正确的提现金额',
        type: 'warning',
      })
      return false
    }
    const res = await withdrawal({
      shopName: details.value.shopName, // 店铺名称
      shopCode: details.value.shopCode, // 店铺编码
      bankName: details.value.bankName, // 银行名称
      bankCard: details.value.bankCard, // 银行卡号
      collectionName: details.value.collectionName, // 收款人姓名
      withdrawalMoney: form.value.amount // 提现金额
    })
    if (res.code === '') {
      ElMessage({
        message: '成功',
        type: 'success'
      })
      isVisible.value = false
    }
  } else {
    isVisible.value = false
    router.push({
      path: 'account'
    })
  }
}
// 全部提现
const getAllAmount = () => {
  form.value.amount = cardList.value[2].money
}
// 初始化查询所有数据
const getAll = async () => {
  try {
    tableLoading.value = true
    const res = await getFinanceCount(searchForm.value)
    if (res.code === '') {
      tableData.value = res.data.finances
      cardList.value[0].money = res.data.turnover
      cardList.value[1].money = res.data.frozenMoney
      cardList.value[2].money = res.data.withdrawableMoney
      cardList.value[3].money = res.data.withdrawableStayMoney
    }
  } finally {
    tableLoading.value = false
  }
}
// 查询明细
const getAlls = async () => {
  try {
    detailTableLoading.value = true
    const res = await getDetails(moneyForm.value)
    if (res.code === '') {
      tableDatas.value = res.data.list
      total.value = res.data.total
    }
  } finally {
    detailTableLoading.value = false
  }
}
// 查询是否绑定银行卡
const getBankType = async () => {}
// 中间部分
const hidden = (str, frontLen, endLen) => {
  let endLenData = 0
  if (str.length !== 2) {
    endLenData = endLen
  }
  const len = str.length - frontLen - endLenData
  let xing = ''
  for (let i = 0; i < len; i++) {
    xing += '*'
  }
  return (
    str.substring(0, frontLen) +
    xing +
    str.substring(str.length - endLenData)
  )
  // return str
}
</script>

<style lang="scss" scoped>
.finance_page {
  width: 100%;
  height: 100%;
  .topCard {
    padding: 20px;
  }
  .clearfix {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .leftBox {
    flex: 1;
    .leftText {
      font-size: 24px;
      font-weight: bold;
      color: #333333;
    }
    .leftTip {
      font-size: 14px;
      color: #999999;
      margin-left: 20px;
    }
  }
  .rightBtn {
    width: 100px;
    height: 38px;
    background: #3a68f2;
    border-radius: 4px;
    color: #ffffff;
    float: right;
  }
  .cardList {
    display: flex;
    align-items: center;
    .cardItem {
      padding: 30px;
      flex: 1;
    }
    .cardDetal {
      .cardMoney {
        font-size: 40px;
        font-weight: bold;
        color: #ffae11;
        margin-bottom: 20px;
        text-align: center;
      }
      .cardText {
        font-size: 18px;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #333333;
        img {
          width: 20px;
          height: 20px;
          margin-left: -7px;
        }
      }
    }
  }
}
// .tableBox {
//   padding: 20px;
// }
.tabList {
  padding: 20px;
  background-color: #FFFFFF;
}
.rightSearch {
  position: absolute;
  right: 20px;
  z-index: 999;
  :deep(.el-input__wrapper) {
    width: 100%;
  }
}
.text_tip {
  margin-left: 50px;
}
.sub_text {
  cursor: pointer;
}
</style>
